package logic

import (
	"context"
	"errors"
	"video-management-system/cache"
	"video-management-system/model"
	"video-management-system/pkg"

	"video-management-system/userrpc/internal/svc"
	"video-management-system/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *LoginLogic) Login(in *userrpc.LoginRequest) (*userrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var findUser model.User
	if err := findUser.FindUserByPhone(model.DB, in.Phone); err != nil {
		return nil, err
	}
	if in.Types == 1 {
		if findUser.ID == 0 {
			return nil, errors.New("账号不存在")
		}
		if findUser.Password != pkg.Str(in.Password) {
			return nil, errors.New("密码错误")
		}
		if findUser.AccountStatus == 1 {
			return nil, errors.New("账号已禁用，请联系管理员”")
		}
	} else if in.Types == 2 {
		if findUser.ID == 0 {
			return nil, errors.New("账号不存在")
		}
		result, _ := cache.Rdb.Get(l.ctx, "sms"+in.Phone).Result()
		if result == "" {
			return nil, errors.New("请发送验证码")
		}
		if result != in.SandCode {
			return nil, errors.New("验证码错误")
		}
	}

	return &userrpc.LoginResponse{
		UserId: int64(findUser.ID),
	}, nil
}
